package com.heima.wemedia.builder;

import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;

import java.util.Date;

/**
 * @author 黄晏凯
 */
public class ArticleDtoBuilder {
    private WmNews wmNews;
    private WmUserMapper wmUserMapper;
    private WmChannelMapper wmChannelMapper;

    private ArticleDto articleDto = new ArticleDto();

    /**
     * 文章dto建设者
     *
     * @param wmNews          wm新闻
     * @param wmChannelMapper wm通道映射器
     * @param wmUserMapper    wm用户映射器
     */
    public ArticleDtoBuilder(WmNews wmNews, WmUserMapper wmUserMapper, WmChannelMapper wmChannelMapper) {
        this.wmNews = wmNews;
        this.wmUserMapper = wmUserMapper;
        this.wmChannelMapper = wmChannelMapper;
    }

    /**
     * 构建属性拷贝
     *
     * @return {@link ArticleDtoBuilder}
     */
    public ArticleDtoBuilder buildBeanCopy() {
        BeanUtils.copyProperties(wmNews, articleDto);
        return this;
    }

    /**
     * 构建作者对象到dto
     *
     * @return {@link ArticleDtoBuilder}
     */
    public ArticleDtoBuilder buildAuthor() {
        if (null != wmNews.getUserId()) {
            WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
            articleDto.setAuthorId((long) wmNews.getUserId());
            articleDto.setAuthorName(wmUser.getName());
        }
        return this;
    }

    /**
     * 构建频道对象到dto
     *
     * @return {@link ArticleDtoBuilder}
     */
    public ArticleDtoBuilder buildChannel() {
        if (null != wmNews.getChannelId()) {
            WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
            articleDto.setChannelName(wmChannel.getName());
        }
        return this;
    }

    /**
     * 构建基本信息到dto
     *
     * @return {@link ArticleDtoBuilder}
     */
    public ArticleDtoBuilder buildBasic() {
        articleDto.setLayout(wmNews.getType());
        articleDto.setCreatedTime(new Date());
        articleDto.setCollection(0);
        articleDto.setComment(0);
        articleDto.setViews(0);
        articleDto.setLikes(0);
        if (wmNews.getArticleId() != null) {
            articleDto.setId(wmNews.getArticleId());
        }
        return this;
    }

    /**
     * 返回dto对象
     *
     * @return {@link ArticleDto}
     */
    public ArticleDto builder() {
        return articleDto;
    }
}